package com.work.mdass.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.work.mdass.domain.Result;
import com.work.mdass.domain.User;
import com.work.mdass.service.UserService;
import com.work.mdass.util.UserResultUtil;

/*
 * 用户控制器
 */
@Controller
@RequestMapping("/admin/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	/*
	 * 获得所有老师
	 */
	@GetMapping("/listUser")
	@ResponseBody
	public List<User> listUser(){
		
		return userService.getAll();
	}
	/*
	 * 增加一名老师
	 */
	@PostMapping("/save")
	@ResponseBody
	public Result<User> save(@Valid User user,BindingResult bindingResult){
		
		if(bindingResult.hasErrors()){
			
			return UserResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
		}
		
		return UserResultUtil.success(userService.addUser(user));
	}
	/*
	 * 修改个人信息
	 */
	@PostMapping("/updata")
	@ResponseBody
	public Result<User> updata(@Valid User user,BindingResult bindingResult){
		
		if(bindingResult.hasErrors()) {
			return UserResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
		}
		return UserResultUtil.success(userService.updataUser(user));
	}
	/*
	 * 删除教师信息
	 */
	@DeleteMapping("/delete/{id}")
	@ResponseBody
	public Result<User> delete(@PathVariable("id") Integer id){
		userService.deleteUser(id);
		return UserResultUtil.success();
	}
	/*
	 * 用户登陆后获得个人信息
	 */
	@PostMapping("/login")
	@ResponseBody
	public Result<User> login(@RequestParam(required = false) Integer tSerial){
		return UserResultUtil.success(userService.getUserByTSerial(tSerial));
	}
	/*
	 * 通过名称查找教师
	 */
	@PostMapping("/byName/{tName}")
	@ResponseBody
	public Result<User> getUserByTName(@PathVariable("tName") String tName){
		return UserResultUtil.success(userService.getUserByTName(tName));
	}
	/*
	 * 通过关键字查询
	 */
	@PostMapping("/byKeyWord")
	@ResponseBody
	public Map<Object,Object> getByKeyWord(@RequestParam(required = false) String keyWord){
		
		return userService.findByKeyWord(keyWord);
	}
}
